/**
 * 初始化用户信息并初始化购物车
 */
const getUserInfo = (openid) => {
	const that = this
	const db = wx.cloud.database().collection('user')
	db.where({
		_openid: openid
	}).get({
		success: (res) => {
			if (res.data.length === 1) {
				uni.setStorageSync('user', res.data[0])
				wx.hideLoading();
				const pages = getCurrentPages()
				const perpage = pages[pages.length - 1]
				perpage.onLoad()
				uni.switchTab({
					url:'/pages/index/index'
				})
			} else if (res.data.length > 1) {
				res.data.forEach((item, index) => {
					if (index > 0) {
						db.doc(item._id).remove()
					}
				})
				uni.setStorageSync('user', res.data[0])
				wx.hideLoading();
				const pages = getCurrentPages()
				const perpage = pages[pages.length - 1]
				perpage.onLoad()
				uni.switchTab({
					url:'/pages/index/index'
				})
			} else {
				wx.hideLoading();
				uni.navigateTo({
					url:'/pages/user/login/login'
				})
			}
		},
		fail: (err) => {
			wx.hideLoading();
			//////console.log(err);
		}
	})
}

const getOpenid = () => {
	wx.showLoading({
		title: '初始化用户信息..',
		mask: true,
	})
	wx.cloud.callFunction({
		name: 'getOpenid',
		success(res) {
			console.log("res",res);
			getUserInfo(res.result.openid)
		}
	})
}

const wxLogin = () => {
	wx.getUserProfile({
		lang: 'zh_CN',
		desc: '用户登录',
		success: (res) => {
			const user = {
				...res.userInfo
			};
			wx.cloud.callFunction({
				name: 'getOpenid',
				success(res) {
					const db = wx.cloud.database().collection('user')
					db.where({
						_openid: res.result.openid,
					}).get({
						success: (res2) => {
							if (res2.data.length === 0) {
								db.add({
									data: user,
									success: (res2) => {
										getOpenid()
									}
								})
							}
						}
					})
				}
			})

		},
	})
}

export {
	getUserInfo,
	getOpenid,
	wxLogin
}